package com.hyperfix.simulator.timer;

import com.hyperfix.models.simulator.pojos.FlowTable;
import com.hyperfix.simulator.mapper.FlowTableMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author JiangChunYu
 * 2024/4/19
 */
@Slf4j
@Component
public class FlowTableRegistrar implements DisposableBean {
    @Resource
    private FlowTableMapper flowTableMapper;

    private static final Map<Integer, FlowTable> flowTables = new ConcurrentHashMap<>(16);

    private static final long FLOW_THRESHOLD = 3000_0000L;

    public void addFlowTable(Integer pipelineId, FlowTable flowTable) {
        flowTables.put(pipelineId, flowTable);
    }

    public static long getFlow(Integer pipelineId) {
        FlowTable flowTable = flowTables.get(pipelineId);
        return flowTable.getValue() - flowTable.getYesterdayValue();
    }

    @Override
    public void destroy() {
        flowTables.clear();
    }

    /**
     * 每10分钟保存一次数据
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void restoreFlowTable() {
        flowTables.forEach((pipelineId, flowTable) -> {
            flowTableMapper.updateById(flowTable);
            log.info("管线{}流量表已保存", pipelineId);
        });
    }

    /**
     * 运行流表表
     */
    @Scheduled(cron = "*/1 * * * * ?")
    public void runFlowTable() {
        flowTables.forEach((pipelineId, flowTable) -> {
            flowTable.increase();
            log.info("管线{}流量表: {}", pipelineId, flowTable.getValue());
        });
    }

    /**
     * 每天凌晨12点检查流量表是否即将溢出 若是则重置流量表
     * 每天凌晨12点保存昨天流量表最大值
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void resetFlowTable() {
        flowTables.forEach((pipelineId, flowTable) -> {
            if (Long.MAX_VALUE - flowTable.getValue() <= FLOW_THRESHOLD) {
                flowTable.setValue(0L);
                flowTable.setYesterdayValue(0L);
                flowTable.setCalibrationTime(LocalDateTime.now());
                flowTableMapper.updateById(flowTable);
                log.info("管线{}流量表重置", pipelineId);
                return;
            }
            flowTable.setYesterdayValue(flowTable.getValue());
            flowTableMapper.updateById(flowTable);
            log.info("管线{}流量表保存昨天最大值", pipelineId);
        });
    }
}
